package a09_贪心算法;


import java.util.Arrays;

public class a09_K次取反后最大化的数组和复习2 {


    public static void main(String[] args) {
        System.out.println(largestSumAfterKNegations(new int[]{4,2,3}, 1));
    }

    //顺序：负数从小到大，然后正数(包含负数)将最小的反复取

    //按照绝对值排序：
    public static int largestSumAfterKNegations(int[] nums, int k) {
        //按照绝对值从大到小
        Integer[] integers = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        Arrays.sort(integers, (item1,item2) -> Math.abs(item2) - Math.abs(item1));

        for (int i = 0; i < integers.length && k > 0; i++) {
            if(integers[i] < 0){
                integers[i] = integers[i] * -1;
                k--;
            }
        }

        while (k > 0){
            integers[integers.length-1] = integers[integers.length-1] * -1;
            k--;
        }

        return Arrays.stream(integers).mapToInt(i -> i).sum();
    }
}
